package com.group.nepm.common.controller;

import com.group.common.users.NEPMUser;
import com.group.common.utils.MyUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

public class NEPMLoginViewController {

    @FXML
    private Button But_login;
    @FXML
    private TextField Txt_adminName;
    @FXML
    private PasswordField Psd_adminPassword;

    //跳转到登陆界面
    public void switchToindex(ActionEvent event) throws IOException {
        if (Txt_adminName.getText().isEmpty() || Psd_adminPassword.getText().isEmpty()){
            MyUtils.showAlert("登录失败","用户名或密码未输入","请输入用户名或密码", Alert.AlertType.INFORMATION);
            return;
        }
        ArrayList<NEPMUser> Admin = MyUtils.readFileToArrayList("group/data/nepm_userdata_arraylist.dat");
        if(Admin == null || Admin.isEmpty()){
            MyUtils.showAlert("登录失败","系统内尚不存在用户","请重试", Alert.AlertType.INFORMATION);
            return;
        }
        String adminName = Txt_adminName.getText();
        String password = Psd_adminPassword.getText();
        if (checkUserName(Admin,adminName)){
            if(checkPassword(Admin,adminName,password)){
                MyUtils.showAlert("登录成功","欢迎",adminName, Alert.AlertType.INFORMATION);
                MyUtils.navigateToView(event,"group/nepm/common/view/index.fxml");
                return;
            }
            else {
                MyUtils.showAlert("登录失败","密码错误","请重新输入密码", Alert.AlertType.INFORMATION);
                return;
            }
        }
        else {
            MyUtils.showAlert("登录失败","用户不存在","请重新输入", Alert.AlertType.INFORMATION);
            return;
        }
    }

    //检查用户是否存在
    private Boolean checkUserName(ArrayList<NEPMUser> Admin,String adminName){
        for (NEPMUser user : Admin) {
            if (user.getUsername().equals(adminName)) {
                return true;
            }
        }
        return false;
    }

    //检查密码是否正确
    private Boolean checkPassword(ArrayList<NEPMUser> Admin,String adminName,String password){
        for (NEPMUser user : Admin) {
            if (checkUserName(Admin,adminName) && user.getPassword().equals(password)) {
                return true;
            }
        }
        return false;
    }

    public void initialize() {
        //TODO
    }
}
